package cn.hsw.platform.core.doc.service;

import cn.hsw.platform.core.doc.annotation.AuthPermission;
import cn.hsw.platform.core.doc.contants.AuthConstant;
import cn.hsw.platform.core.redis.RedisUtil;
import cn.hsw.platform.core.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * 获取项目接口信息
 * @author 李子木
 */
@Service
public class AuthReportService {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取方法名 注解 Permission code 并存储至redis
     */
    public void getApiInfo(){
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();

        HashMap<String,Object> permissionMap = new HashMap<>();

        /*遍历map*/
        for (Map.Entry<RequestMappingInfo, HandlerMethod> handlerMethodMap : handlerMethods.entrySet()) {

            RequestMappingInfo requestMappingInfo = handlerMethodMap.getKey();
            HandlerMethod handlerMethod = handlerMethodMap.getValue();
            //获取权限code
            AuthPermission methodAnnotation = handlerMethod.getMethodAnnotation(AuthPermission.class);

            //获取接口地址 多个的
            Set<String> patterns = requestMappingInfo.getPatternsCondition().getPatterns();
            /*获取url集合*/
            for (String url:patterns){
                //将 user/info/{id}这种匹配为 ------
                if (url.contains("{") && url.contains("}")) {
                    url = url.replaceAll("\\{[^}]*\\}", AuthConstant.AUTH_URL_PATTERN);
                }
                //如果没有则略过，则赋值""
                if(Validator.isNull(methodAnnotation)){
                    permissionMap.put(url,AuthConstant.NO_NEED_AUTHENTICATION_DEFAULT_CODE);
                }else{
                    permissionMap.put(url,methodAnnotation.value());
                }
            }

        }
        redisUtil.sSet(AuthConstant.AUTH_AUTHENTICATION_LIST,applicationName);
        redisUtil.del(AuthConstant.AUTH_PREFIX+applicationName);
        redisUtil.hmset(AuthConstant.AUTH_PREFIX+applicationName,permissionMap);
    }
}
